/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.product.remote.RemoteSpecificationInventoryServiceImpl
   Module Description   :

   Date Created      : 2010/2/1
   Original Author   : ellen.li
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.product.remote;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.entity.SpecificationInventory;
import com.yaodian100.ec.product.service.ProductService;

/**
 * @author ellen.li
 * 
 */
public class RemoteSpecificationInventoryServiceImpl implements RemoteSpecificationInventoryService {
	private static Logger logger = LoggerFactory.getLogger(RemoteSpecificationInventoryServiceImpl.class);
	@Autowired
	private ProductService productService;

	@Resource
	private JdbcTemplate jdbcTemplate;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.product.remote.RemoteSpecificationInventoryService#updateInventory(java.lang.String,
	 * java.lang.Long, int)
	 */
	@Override
	public String updateInventory(String productId, String specId, int qty, String transationType, String invHistoryId) {
		String isSuccess = "";
		try {
			if (StringUtils.isEmpty(productId)) {
				isSuccess = "ProductId is Empty!!";
				throw new Exception("ProductId is Empty!!");
			}
			if (StringUtils.isEmpty(specId)) {
				isSuccess = "specId is Empty!!";
				throw new Exception("specId is Empty!!");
			}
			if (StringUtils.isEmpty(transationType)) {
				isSuccess = "transationType is Empty!!";
				throw new Exception("transationType is Empty!!");
			}
			if (StringUtils.isEmpty(invHistoryId)) {
				isSuccess = "invHistoryId is Empty!!";
				throw new Exception("invHistoryId is Empty!!");
			}
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("productId", productId);
			criteria.addEq("specId", Long.parseLong(specId));
			int size = productService.getSpecificationInventory(criteria).size();
			SpecificationInventory specificationInventory;
			if (size == 0) {
				Specification specCheck = productService.getSpecification(Long.parseLong(specId));
				specificationInventory = new SpecificationInventory();
				if (specCheck.getProductId().equals(productId)) {
					specificationInventory.setProductId(productId);
					specificationInventory.setSpecId(Long.parseLong(specId));
					specificationInventory.setAvailableInventory(0);
					specificationInventory.setCancelInventory(0);
					specificationInventory.setSoldInventory(0);
				} else {
					isSuccess = "ProductId is not match specId!!";
					throw new Exception("ProductId is not match specId!!");
				}
			} else {
				specificationInventory = productService.getSpecificationInventory(criteria).get(0);
			}

			// 可销售量(available-sold+cancel)
			int inv = specificationInventory.getAvailableInventory() - specificationInventory.getSoldInventory()
					+ specificationInventory.getCancelInventory();
			if ("971".equals(transationType) || "973".equals(transationType)) { // 商城庫存管理
				specificationInventory.setAvailableInventory(specificationInventory.getSoldInventory()
						- specificationInventory.getCancelInventory() + qty);
			} else if ("991".equals(transationType) && inv < 0) {// 991 虚拟数量,可销售量<0
				// (处理可售量为负的问题，pm设数量后还是无法卖),available_inventory
				// =
				// sold_inventory - cancel_inventory + 数量
				specificationInventory.setAvailableInventory(specificationInventory.getSoldInventory()
						- specificationInventory.getCancelInventory() + qty);
			} else if ("994".equals(transationType)) {// 994 回复实际库存available_inventory = 数量
				specificationInventory.setAvailableInventory(qty);
			} else {
				int availableInvetory = specificationInventory.getAvailableInventory();
				specificationInventory.setAvailableInventory(availableInvetory + qty);
			}

			// productService.saveSpecificationInventory(specificationInventory);
			StringBuffer sqlSb = new StringBuffer();
			sqlSb.append("select valid_id from EC_SPEC_INVENTORY_VALID where valid_id='").append(invHistoryId).append("'");
			int chkInvHistoryId = jdbcTemplate.queryForList(sqlSb.toString()).size();
			if (chkInvHistoryId == 0) {
				productService.saveSpecificationInventoryAndInvalid(specificationInventory, invHistoryId);
			}
			productService.checkIsSoldOut(productId);
			isSuccess = "true";
			// logger.info("product:{},specid:{},qty:{},total:{}", new Object[] { productId, specId, qty,
			// specificationInventory.getAvailableInventory() });
		} catch (Exception e) {
			logger.error("updateInventory failed:", e);
			isSuccess = "updateInventory failed_product_productId:" + productId + ",specId:" + specId + ",qty:" + qty;
		}
		return isSuccess;
	}

	@Override
	public String updateInventoryArray(String[] productId, String[] specId, String[] qty, String[] transationType,
			String[] invHistoryId) {
		String isSuccess = "true";
		try {
			List<String> invHisIds = new ArrayList<String>();
			for (int i = 0; i < invHistoryId.length; i++) {
				if (invHisIds.contains(invHistoryId[i])) {
					isSuccess = "Error_productId1:" + productId[i] + ",specId:" + specId[i] + ",qty:" + qty[i];
					break;
				}

				if (StringUtils.isEmpty(productId[i]) || StringUtils.isEmpty(specId[i])
						|| StringUtils.isEmpty(transationType[i]) || StringUtils.isEmpty(invHistoryId[i])
						|| StringUtils.isEmpty(qty[i])) {
					isSuccess = "Error_productId2:" + productId[i] + ",specId:" + specId[i] + ",qty:" + qty[i];
					break;
				}

				if (!isNumeric(qty[i])) {
					isSuccess = "Error_productId3:" + productId[i] + ",specId:" + specId[i] + ",qty:" + qty[i];
					break;
				}

				Specification specCheck = productService.getSpecification(Long.parseLong(specId[i]));
				if (!specCheck.getProductId().equals(productId[i])) {
					isSuccess = "Error_productId4:" + productId[i] + ",specId:" + specId[i] + ",qty:" + qty[i];
					break;
				}

				invHisIds.add(invHistoryId[i]);
			}
			if (isSuccess.equals("true")) {
				for (int i = 0; i < invHistoryId.length; i++) {
					isSuccess = updateInventory(productId[i], specId[i], Integer.parseInt(qty[i]), transationType[i],
							invHistoryId[i]);

					if (!isSuccess.equals("true")) {
						break;
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			isSuccess = e.getMessage().toString();
		}
		return isSuccess;
	}

	public boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	@Override
	public String searchInfo1(String[] specIds) {
		if (null == specIds || specIds.length == 0) {
			return "";
		}
		StringBuffer sqlSb = new StringBuffer();
		sqlSb.append("select c.spec_id , c.available_inventory-c.sold_inventory + c.cancel_inventory inv,( ");
		sqlSb.append("select nvl(sum(a.qty),0) from ec_order_detail a , ec_order_main b ");
		sqlSb
				.append("where b.order_id = a.order_id and b.order_st in ('00','10','20','05') and b.order_type in ('1','2') ");
		sqlSb.append("and a.prod_spec_id = c.spec_id ) not_sync ");
		sqlSb.append("from ec_specification_inventory c where c.spec_id in( ");
		for (int i = 0; i < specIds.length; i++) {
			String specId = specIds[i];
			if (i != 0) {
				sqlSb.append(", ");
			}
			sqlSb.append("'");
			sqlSb.append(specId);
			sqlSb.append("'");
		}
		sqlSb.append(" )");

		StringBuffer outputSb = new StringBuffer();
		outputSb.append("spec_id,inv,not_sync\n");
		List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sqlSb.toString());
		if (null != resultList && (!resultList.isEmpty())) {
			for (Map<String, Object> data : resultList) {
				outputSb.append(data.get("spec_id")).append(",");
				outputSb.append(data.get("inv")).append(",");
				outputSb.append(data.get("not_sync")).append("\n");
			}
		}
		return outputSb.toString();
	}

	@Override
	public String searchInfo2(int qty1, int qty2) {
		StringBuffer sqlSb = new StringBuffer();
		sqlSb.append("select c.spec_id , c.available_inventory-c.sold_inventory + c.cancel_inventory inv ,( ");
		sqlSb.append("select nvl(sum(a.qty),0) from ec_order_detail a , ec_order_main b ");
		sqlSb
				.append("where b.order_id = a.order_id and b.order_st in ('00','10','20','05') and b.order_type in ('1','2') ");
		sqlSb.append("and a.prod_spec_id = c.spec_id ) not_sync ");
		sqlSb.append("from ec_specification_inventory c where ");
		sqlSb.append("(c.available_inventory+c.sold_inventory - c.cancel_inventory) >= ").append(qty1).append(" or ");
		sqlSb.append("(c.available_inventory+c.sold_inventory - c.cancel_inventory) <= ").append(qty2);

		StringBuffer outputSb = new StringBuffer();
		outputSb.append("spec_id,inv,not_sync\n");
		List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sqlSb.toString());
		if (null != resultList && (!resultList.isEmpty())) {
			for (Map<String, Object> data : resultList) {
				outputSb.append(data.get("spec_id")).append(",");
				outputSb.append(data.get("inv")).append(",");
				outputSb.append(data.get("not_sync")).append("\n");
			}
		}
		return outputSb.toString();
	}

}
